import { SysUser } from '@common/domain/sys_user';
import { db } from '../database/db';

export async function getUserList(offset: number|string = 0, limit: number|string = 10) {
    // 基础条件
    const baseQuery = db.selectFrom('sys_user').where('del_flag', '=', '0');

    // 查询总数
    const [{ count }] = await baseQuery
        .select(db.fn.countAll().as('count'))
        .execute();
    const total = Number(count);

    if (total === 0) {
        return { list: [], total: 0 };
    }

    // 查询列表
    const list = await baseQuery
        .selectAll()
        .orderBy('user_id', 'asc')
        .offset(Number(offset))
        .limit(Number(limit))
        .execute();

    return { list, total };
}

export async function getUserById(user_id: number) {
  return await db.selectFrom('sys_user')
    .selectAll()
    .where('user_id', '=', user_id)
    .executeTakeFirst();
}

export  const createUser = async (data: SysUser) =>{ 
  const result = await db.insertInto('sys_user').values([data]).executeTakeFirst();
  return 0;
}

export async function updateUser(user_id: number, data: Partial<SysUser>) {
  const result = await db.updateTable('sys_user')
    .set(data)
    .where('user_id', '=', user_id)
    .executeTakeFirst();
  return result.numUpdatedRows;
}

export async function deleteUser(user_id: number) {
  const result = await db.updateTable('sys_user')
    .set({ del_flag: '2' })
    .where('user_id', '=', user_id)
    .executeTakeFirst();
  return result.numUpdatedRows;
}

export async function getUserByUsername(user_name: string) {
  return await db.selectFrom('sys_user')
    .selectAll()
    .where('user_name', '=', user_name)
    .executeTakeFirst();
} 
export async function updateUserRole(user_id: number, role_ids: number[]) {
  // 先删除
 await db.deleteFrom('sys_user_role').where('user_id', '=', user_id).execute();
  // 再插入
  const result = await db.insertInto('sys_user_role').values(role_ids.map(role_id => ({ user_id, role_id }))).execute();
  console.log(result);
  return Number(result);
}

export async function updateUserPassword(user_id: number, password: string) {
  const result = await db.updateTable('sys_user')
    .set({ password })
    .where('user_id', '=', user_id)
    .executeTakeFirst();
  return result.numUpdatedRows;
}